<template>
	<view ref='MainPage' class="teachmain">
		<view class="cu-custom" :style="{height: $wanlshop.wanlsys().height + 'px' }">
			<view class="cu-bar fixed">
				<view class="action" @tap="Back()">
					<text class="wlIcon-fanhui1"></text>
				</view>
				<view class="content" :style="{top: $wanlshop.wanlsys().top + 'px'}">
					<!-- 线上考试 -->
				</view>
				<!-- <view class="action" @tap="showModal('share')">
						<text class="wlIcon wlIcon-fenxiang"></text>
					</view> -->
			</view>
		</view>
		<!-- <view v-show="!finishBtn"  class="examItem">
				<view class="">
					练习结束
				</view>
				<view class="">
					
					共{{examList.length}}道题，
					回答正确<text style="color: #007EFF;">{{examList.length-WrongNum}}</text>道题，
					错误 <text style="color: #E81A24;" >{{WrongNum}}</text>道题；
					正确率{{(examList.length-WrongNum)/examList.length.toFixed(2)}}%。
				</view>
			</view> -->
		<view v-for="(i,n) in examList" :key='n' class="examItem">
			<exam-modal ref='examModal' :info='i' :index='n' :daAn='i.daan' :daAnDesc='i.analysis' :choses='i.extend'
				@sendAnswer='receiveAnswer' @ChoseItem='AddItem' />
		</view>
		<view v-show="finishBtn" class="">
			<button @click="FinishPractice" class="finish" type="default">提交</button>
		</view>
		<uni-popup :is-mask-click='false' :mask-click='false' style="background-color:rgba(0,0,0,.4);" ref="inputDialog"
			type="center">
			<view class="FormContent">
				<uni-forms ref="form" :modelValue="formData" :rules="rules">

					<uni-forms-item label="头像" name="img">
						<uni-file-picker v-model="formData.imageValue"  mode="grid"
							 disable-preview :del-icon="false" return-type="object"
							:image-styles="imageStyles" :limit="1" @progress="progress" @success="success" @fail="fail"
							@select="select" />
					</uni-forms-item>
					<uni-forms-item label="姓名">
						<uni-easyinput v-model="formData.name" placeholder="请输入姓名" />
					</uni-forms-item>
					<uni-forms-item label="民族">
						<uni-easyinput v-model="formData.nation" placeholder="请输入民族" />
					</uni-forms-item>
					<uni-forms-item label="生日">
						<uni-datetime-picker v-model="formData.birthday " type="date" />
					</uni-forms-item>
					<uni-forms-item label="身份证号">
						<uni-easyinput v-model="formData.id_no" placeholder="请输入身份证号" />
					</uni-forms-item>
					<uni-forms-item label="联系电话">
						<uni-easyinput v-model="formData.mobile" placeholder="请输入联系电话" />
					</uni-forms-item>
					<uni-forms-item label="验证码" class="Yzm">
						<uni-easyinput focus v-model="formData.YZM" placeholder="请输入验证码" />
						<view class="get-code" :style="{'color':getCodeBtnColor}" @click.stop="getCode()">
							{{getCodeText}}
						</view>
					</uni-forms-item>

				</uni-forms>
				<button class="submitBtn" @click="submit()">提交</button>
			</view>
			<!-- 33333 -->
			<!-- <uni-popup-dialog ref="inputClose"  mode="input" title="输入内容" value="对话框预置提示内容!"
								placeholder="请输入内容" @confirm="dialogInputConfirm"></uni-popup-dialog> -->
		</uni-popup>
		<uni-popup is-mask-click='false' :mask-click='false' style="background-color:rgba(0,0,0,.4);" id="SureSubmit"
			ref="SureSubmit" type="dialog">
			<view class="container">
				<view class="text">
					{{NoticeText}}
				</view>

				<view class="btnContainer">
					<button type="default" @click="$wanlshop.back(1)">退出</button>
					<button type="primary" @click="$refs.SureSubmit.close()"
						style="background: #8CBF6B;color: #fff;">继续答题</button>
				</view>
			</view>
		</uni-popup>
		<uni-popup is-mask-click='false' :mask-click='false' style="background-color:rgba(0,0,0,.4);" id="notFull"
			ref="notFull" type="dialog">
			<view class="container">
				<view class="text">
					您有{{examList.length-answerNum}}道题未作答,确认提交试卷吗
				</view>

				<view class="btnContainer">
					<button type="default" @click="$refs.notFull.close()">继续答题</button>
					<button type="primary" @click="FinishPractices()" style="background: #8CBF6B;color: #fff;">确认提交</button>
				</view>
			</view>
		</uni-popup>
		<view v-show="finishExam" class="Scores">
			得分： {{ScoreInfo.score}}分
			
			共 {{ScoreInfo.totalNumber}}道题，回答正确 {{ScoreInfo.successNumber}}道题，错误 {{ScoreInfo.errorNumber}}道题
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	import ExamModal from './components/ExamModal.vue'
	import { appurl} from '@/common/config/config.js'
	export default {
		components: {
			ExamModal
		},
		computed: {

		},

		data() {
			return {
				imageStyles: {
					width: 64,
					height: 64,
					border: {
						color: "#eee",
						width: 1,
						style: 'solid',
						radius: '2px'
					}
				},
				headHeight: 75,
				windowHeight: 0,
				examList: [],
				headTop: 0,
				page: 1,
				value: '1',
				teacherList: [],
				WrongNum: 0,
				finishBtn: true,
				contentText: {
					contentdown: '下拉加载更多',
					contentrefresh: '加载中',
					contentnomore: '我是有底线的'
				},
				getCodeBtnColor: '',
				formData: {
					name: '',
					nation: '',
					cret: "",
					birthday: '',
					image: '',
					imageValue: {},
					data: {},
					exam_id: '',
					exam_bank_cate_id: '',
					mobile: '',
					id_no: '',
					YZM: ''

				},
				getCodeText: "验证码",
				rules: {
					// 对name字段进行必填验证

				},
				answerList: [],
				getCodeisWaiting: false,
				cateid: '',
				NoticeText: '',
				answerNum: 0,
				finishExam:false,
				ScoreInfo:{}
			};
		},
		created() {

			// this.getListData(this.$route.query.id)

		},
		mounted() {

		},
		onLoad(options) {
			this.getListData(options.id)
			this.cateid = options.id
		},
		onShow() {
			// #ifdef APP-PLUS
			plus.navigator.setFullscreen(false);
			// #endif
			// 计算页面尺寸
			let sys = this.$wanlshop.wanlsys();
			this.headTop = sys.top;
			this.headHeight = sys.height + uni.upx2px(60);
			this.windowHeight = sys.windowHeight;
			setTimeout(() => {
				uni.setNavigationBarColor({
					frontColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarTextStyle : '',
					backgroundColor: this.$store.state.common.modulesData.homeModules.page ?
						this.$store.state.common.modulesData.homeModules.page.style
						.navigationBarBackgroundColor : ''
				});
			}, 200);

		},
		onReady() {
			// 判断网络类型
			this.$refs.inputDialog.open()
		},
		methods: {
			select(e) {
				console.log('选择文件：', e)
				let vm = this
				// var forms = new FormData()

				uni.uploadFile({
					url: appurl+'/common/upload',
					filePath: e.tempFilePaths[0],
					name: 'file', //后台接收字段名
					// formData: this.formdata,
					header: {
						// "Content-Type": "multipart/form-data"

					},
					success: (res) => {
						console.log(JSON.parse(res.data))
						let result = JSON.parse(res.data)
						if (result.code == 1) {
							vm.formData.image = result.data.url
						}
						// if(res.)
					},
					fail: (err) => {}
				})

			},
			getCode() {
				uni.hideKeyboard() //隐藏已经显示的软键盘，如果软键盘没有显示则不做任何操作。
				if (this.getCodeisWaiting) {
					return;
				}
				if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.formData.mobile))) { //校验手机号码是否有误
					uni.showToast({
						title: '请填写正确手机号码',
						icon: "none"
					});
					return false;
				}
				this.getCodes()
				this.getCodeText = "发送中..." //发送验证码
				this.getCodeisWaiting = true;
				// this.getCodeBtnColor = "rgba(255,255,255,0.5)" //追加样式，修改颜色
				//示例用定时器模拟请求效果
				//setTimeout(()用于在指定的毫秒数后调用函数或计算表达式

				setTimeout(() => {}, 1000)
			},
			//setTimer： 需要每隔一段时间执行一件事的的时候就需要使用SetTimer函数

			getCodes() {
				let vm = this
				vm.$api.get({
					url: '/user/send?mobile=' + vm.formData.mobile,
					success: res => {
						uni.showToast({
							title: '验证码已发送',
							icon: "none"
						}); //弹出提示框
						//示例默认1234，生产中请删除这一句。

						vm.setTimer(); //调用定时器方法


						// this.BannerList = res.banner
					}
				})
			},
			setTimer() {
				let holdTime = 60; //定义变量并赋值
				this.getCodeText = "重新获取(60)"
				//setInterval（）是一个实现定时调用的函数，可按照指定的周期（以毫秒计）来调用函数或计算表达式。
				//setInterval方法会不停地调用函数，直到 clearInterval被调用或窗口被关闭。
				this.Timer = setInterval(() => {
					if (holdTime <= 0) {
						this.getCodeisWaiting = false;
						// this.getCodeBtnColor = "#ffffff";
						this.getCodeText = "获取验证码"
						clearInterval(this.Timer); //清除该函数
						return; //返回前面
					}
					this.getCodeText = "重新获取(" + holdTime + ")"
					holdTime--;
				}, 1000)
			},
			change(e) {

			},
			getListData(id) {
				let vm = this
				vm.$api.get({
					url: '/exam/examList?category_id=' + id,

					success: res => {
						console.log(res)
						vm.examList = res.list
						vm.examInfo = res.exam_info
						// this.BannerList = res.banner
					}
				})
			},
			submit() {
				let vm = this
				this.$api.post({
					url: '/topic/verifyCode',
					data: {
						mobile: this.formData.mobile,
						code: this.formData.YZM
					},
					success: (res) => {
						console.log(res)
						if (res.length == 0) {
							vm.submitForm()

						} else {
							uni.showToast({
								title: '异常错误！',
								icon: "error"
							}); //弹出提示框
						}
						// this.BannerList = res.banner
					}
				})

			},
			submitForm() {
				// name: '',
				// nation: '',
				// cret: "",
				// birthday: '',
				// image: '',
				// data: {},
				// exam_id: '',
				// exam_bank_cate_id: '',
				// mobile: '',
				// id_no: '',
				// YZM:''
				console.log(this.formData)
				if (!this.formData.name ||
					!this.formData.nation || !this.formData.image ||
					!this.formData.mobile || !this.formData.id_no

				) {
					uni.showToast({
						title: '请填写所有信息！',
						icon: "none"
					});
					return false
				} else {
					this.$refs.inputDialog.close()
				}


			},
			Back() {
				if(!this.finishExam){
					this.NoticeText = '试卷还未提交,确认退出吗？'
					this.$refs.SureSubmit.open()
					
				}else{
					this.$wanlshop.back(1)
				}
			
			},
			// Back(){
			// let allchild = this.$refs.examModal

			// allchild.forEach((item, n) => {
			// 	this.$refs.examModal[n].judge()

			// })	
			// },

			AddItem(value) {

				if (value) {
					this.answerNum++
				}
				setTimeout(() => {
					console.log(this.answerNum)
					if (this.answerNum < this.examList.length) {
						this.$refs.notFull.open()
					}else{
						this.FinishPractices()
					}
				}, 100)

			},
			receiveAnswer(value) {
				console.log(value)
		
				this.answerList.push(value)
				this.finishBtn = false
					
				if(this.answerList.length==this.examList.length){
					setTimeout(()=>{
						this.LastSubmit()
					},200)
						document.body.scrollTop = document.documentElement.scrollTop = 0;
				}
			
			
				// this.$refs.MainPage.scrollTop(0)
			},
			FinishPractice() {
				let allchild = this.$refs.examModal
				allchild.forEach((item, n) => {
					this.$refs.examModal[n].judges()

				})
			},
				
			FinishPractices(){
				this.$refs.notFull.close()
				let allchild = this.$refs.examModal
				allchild.forEach((item, n) => {
					this.$refs.examModal[n].judge()
				
				})
			},
			LastSubmit() {
				setTimeout(() => {
					let vm = this;
					console.log(this.formData)
					let answerLists = vm.answerList.slice(0,vm.examList.length)
					vm.$api.post({
						url: '/exam/submit',
						data: {

							name: this.formData.name,
							nation: this.formData.nation,
							cret: this.formData.cret,
							birthday: this.formData.birthday,
							image: this.formData.image,
							data:answerLists ,
							exam_id: vm.examInfo.id,
							exam_bank_cate_id: vm.cateid,
							mobile: this.formData.mobile,
							id_no: this.formData.id_no,
							// YZM:''

						},
						success: (res) => {
							console.log(res)
							uni.showToast({
								title: '考试完成！',
								icon: "success"
							});
							this.finishExam = true
							this.ScoreInfo =res
							// this.BannerList = res.banner
						},
						fail (err) {
							// uni.showToast({
							// 	title: '异常错误！',
							// 	icon: "error"
							// }); //弹出提示框
						}
						
					})
				}, 1000)

			}




		}
	};
</script>

<style lang="scss">
	body {
		background: #fff !important;
	}

	.teachmain {
		background-color: #fff;
		min-height: 100vh;
		padding-bottom: 20rpx;
	}

	.fixed {
		background: #fff;
		height: 90rpx;
	}

	.examItem {
		margin: 30rpx;
		font-size: 26rpx;
		font-family: PingFang-SC-Medium;
		line-height: 40rpx;
		color: #333333;
	}
	.finish {
		margin: 20rpx auto;
		width: 248rpx;
		height: 60rpx;
		background: rgba(255, 255, 255, 0.39);
		border: 2rpx solid #999999;
		opacity: 1;
		border-radius: 10rpx;
		font-size: 26rpx;
		font-family: PingFang-SC-Medium;
		line-height: 60rpx;
	}
	.FormContent {
		background: #fff;
		border-radius: 24rpx;
		width: 630rpx;
		height: 770rpx;
		// /* background: rgba(255, 255, 255, 0.39); */
		padding: 40rpx 64rpx 40rpx 34rpx;
		opacity: 1;
		border-radius: 20rpx;
	}

	/deep/ .uni-forms-item__inner {
		padding: 0;
		margin-top: 10rpx;
	}

	.submitBtn {
		width: 230rpx;
		height: 50rpx;
		background: rgba(140, 191, 107, 0.39);
		opacity: 1;
		font-size: 28rpx;
		font-family: PingFang-SC-Medium;
		margin-top: 20rpx;
		color: #FFFFFF;
		line-height: 50rpx;
	}

	.Yzm {
		position: relative;
	}

	.get-code {
		// width: 80rpx;
		height: 22rpx;
		font-size: 16rpx;
		font-family: PingFang-SC-Medium;
		line-height: 22rpx;
		color: #679C44;
		opacity: 1;
		position: absolute;
		right: 18rpx;
		top: 0;
		bottom: 0;
		margin: auto;
	}

	/deep/ .uniui-clear {
		display: none;
	}

	.container {
		width: 630rpx;
		height: 320rpx;
		background: #fff;
		border-radius: 20rpx;
		margin: 400rpx auto;
		padding-top: 72rpx;
	}

	.text {
		margin: 0 auto 88rpx;
		text-align: center;
	}

	.btnContainer {
		display: flex;
		justify-content: space-around;

		button {
			width: 100px;
			height: 30px;
			background: #fff;
			font-size: 13px;
			font-family: PingFang-SC-Medium-, PingFang-SC-Medium;
			font-weight: normal;
			color: #333333;
		}
	}
	.Scores{
		margin-left: 20rpx;
	}
</style>
